from fastapi import APIRouter, Query,UploadFile,BackgroundTasks
from tortoise.expressions import Q
from app.controllers.marketing.coupons import coupons_controller
from app.controllers.marketing.coupons_rule import coupons_rule_controller
from app.models import CustomerUser, Coupons, CouponsRole
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.marketing import CouponsCreateIn, CouponsUpdate,CouponsCreate
from fastapi.responses import JSONResponse
from app.settings import settings

coupons_router = APIRouter()
model_name = "优惠券发放记录"


@coupons_router.get("/list", summary=f"查看{model_name}列表")
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        user_name: str = Query(None, description=f"用户姓名"),
        type: int = Query(None, description=f"优惠券类型"),
):
    search_user_ids = []
    if user_name:
        search_users = await CustomerUser.filter(name__contains=user_name).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
    q = Q()
    if user_name:
        q &= Q(user_id__in=search_user_ids)
    if type:
        q &= Q(coupons_id=type)
    total, data = await coupons_controller.do_list(page=page, page_size=page_size, search=q)

    user_ids = {orders['user_id'] for orders in data}  # 获取所有的 user_id
    users = await CustomerUser.filter(id__in=user_ids)
    users_dict = {user.id: user.name for user in users}
    type_objs = await coupons_rule_controller.level_list()
    for item in data:
        item['user_name'] = users_dict.get(item['user_id'], "已删除用户")
        item['type_name'] = type_objs[item['coupons_id']]
        item['come_name'] = settings.COUPONS_TYPE[item['come_type']]

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@coupons_router.get("/get", summary=f"查看{model_name}")
async def do_get(
        data_id: int = Query(..., description="ID"),
):
    data = await coupons_controller.do_detail(data_id=data_id)
    return Success(data=data)

@coupons_router.post("/create", summary=f"创建{model_name}")
async def do_create(
        back_tasks: BackgroundTasks,
        category_in: CouponsCreateIn,
):
    back_tasks.add_task(coupons_controller.do_put, category_in=category_in)
    return JSONResponse(content={"code": 200, "message": "开始生成优惠券,请稍后"}, status_code=200)


@coupons_router.post("/update", summary=f"更新{model_name}")
async def do_update(
        category_in: CouponsUpdate,
):
    await coupons_controller.do_update(obj_in=category_in)
    return Success(msg="更新成功")

@coupons_router.delete("/delete", summary=f"删除{model_name}")
async def do_delete(
        data_id: int = Query(..., description="ID"),
):
    await coupons_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")

@coupons_router.get("/expire", summary=f"每日检测{model_name}的到期任务")
async def do_expire(back_tasks: BackgroundTasks):
    back_tasks.add_task(coupons_controller.do_expire)
    return Success(msg="开始检测")
